// app.js
App({
  async onLaunch() {
    // 登录
    await this.login();
  },
  globalData: {
    userInfo: null,
    domain: 'http://zhaoxin.gsdse.cn'
  },
  //登录
  login() {
    const that = this
    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          const that = this
          // console.log(res.code)
          wx.request({
            url: that.globalData.domain + '/api/user/wechatlogin',
            method: "POST",
            header: {
              "content-type": 'application/x-www-form-urlencoded'
            },
            data: {
              code: res.code
            },
            success: res => {
              const data = res.data.data
              console.log("用户信息", data)
              //保存token和openid
              console.log('token', data.token)
              wx.setStorageSync('token', data.token)
              wx.setStorageSync('openId', data.user.openId)
              //保存并返回用户信息
              that.globalData.userInfo = data.user
              resolve(data.user)
            }
          })
        }
      })
    })
  },
  //-----------------------------------
  //工具方法
  //显示信息
  showMessage(msg) {
    wx.showToast({
      title: msg,
      icon: 'none'
    })
  },
  //显示加载中
  showLoading(msg) {
    wx.showToast({
      title: msg,
      icon: "loading"
    })
  },
  //类似规范中提到的qs.Stringify方法
  queryStringify(obj, prefix = '') {
    let str = [];
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        let value = obj[key];
        let k = prefix ? prefix + '[' + key + ']' : key;
        // 如果值是数组或对象，递归处理  
        if (value && typeof value === 'object' && !Array.isArray(value)) {
          str.push(queryStringify(value, k));
        } else if (value !== undefined) { // 忽略undefined值  
          // 处理数组  
          if (Array.isArray(value)) {
            for (let i = 0; i < value.length; i++) {
              str.push(encodeURIComponent(k + '[' + i + ']') + '=' + encodeURIComponent(value[i]));
            }
          } else {
            // 处理基本类型  
            str.push(encodeURIComponent(k) + '=' + encodeURIComponent(value));
          }
        }
      }
    }
    return str.join('&');
  },
  //通过id获取部门信息
  getDeptInfo(deptId) {
    const that = this
    return new Promise((resolve, reject) => {
      wx.request({
        url: that.globalData.domain + '/api/dept/listById',
        method: "GET",
        data: {
          deptId: deptId
        },
        header: {
          "content-type": "application/x-www-form-urlencoded",
          "token": wx.getStorageSync('token')
        },
        success: (res) => {
          const resData = res.data.data
          resolve(resData)
        },
        fail: (err) => {
          console.error(err)
        }
      })
    })
  },
  //获取活动内容
  async getActivityInfo() {
    const that = this 
    // await that.simulateDelay(5);
    return new Promise((resolve, reject) => {
      wx.request({
        url: that.globalData.domain + '/api/activity/list',
        method: "POST",
        header: {
          "content-type": 'application/json',
          "token": wx.getStorageSync('token')
        },
        success: (res) => {
          // console.log(res.data)
          const resdata = res.data
          if (resdata.code === 403) { //token非法
            // getApp().showMessage('token非法！请尝试重启小程序！')
            reject('token非法')
          } else { //成功返回部门信息数组
            var activityInfo = resdata.data
            //处理数据
            if (activityInfo.length) {
              resdata.data.forEach((item, index) => {
                if (!item.recruitNum) { //如果招募数为空则将招募数归零
                  item.recruitNum = 0
                }
              })
            }
            resolve(activityInfo)
          }
        },
        fail: (err) => {
          console.error(err)
          //失败返回失败信息
          if(err.errMsg == "request:fail "){
            reject('ERR_CONNECTION_RESET')
          }
          reject('other')
        }
      })
    })
  },
  //延时锦囊
  simulateDelay(second) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve('延时结束')
        console.log('延时', second, '秒')
      }, second * 1000)
    })
  }
})